package com.fanfan.job;

import com.fanfan.pojo.Article;
import com.fanfan.service.ArticleService;
import com.fanfan.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class UpdateViewCountJob {
    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ArticleService articleService;

    @Scheduled(cron = "0 0/5 * * * ?")
    public void updateViewCount(){
        System.out.println("定时任务执行了");
        //获取redis中的浏览量,map方法可以将对应entry类型的转化为article类型，这里转化为entrySet是为了方便转化
        Map<String, Integer> viewCountMap = redisCache.getCacheMap("article:viewCount");

        List<Article> articles = viewCountMap.entrySet()
                .stream()
                .map(entry -> new Article(Long.valueOf(entry.getKey()), entry.getValue().longValue()))
                .collect(Collectors.toList());//将流转化为list
        //更新到数据库中
        articleService.updateBatchById(articles);

    }
}
